﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using CoreEx.Database.Client;
using LinFu.IoC.Interfaces;
using LinFu.IoC;
using CoreEx.Common.Extensions;
namespace CoreEx.Database.Query
{
    public static class CommandExtensions
    {
        private static IServiceContainer _serviceContainer = Services.ServiceLocator.Container;

        public static IDataReader ExecuteReader(this IDbCommand dbCommand, IQueryExpression queryExpression)
        {
            IDbConnectionInfo dbConnectionInfo = (IDbConnectionInfo) dbCommand.Connection;
            var queryTranslator = _serviceContainer.GetService<IQueryTranslator>(dbConnectionInfo.ProviderName);
            ITranslatedQuery translatedQuery = queryTranslator.Translate(queryExpression);
            dbCommand.CommandType = CommandType.Text;
            dbCommand.CommandText = translatedQuery.Sql;
            translatedQuery.ImplicitParameters.ForEach(p => dbCommand.Parameters.Add(p.Value));
            return dbCommand.ExecuteReader(CommandBehavior.CloseConnection);
        }
    }
}
